
var ws = null;
var queue = new Queue();
queue.dealSyn(handleJsonResult);

function connectToServer() {
	var playerId = dataStorage.get(MyOwner.playerId);
	var userId = dataStorage.get(MyOwner.userId);
	
	// 设定WebSocket,注意协议是ws，请求是指向对应的WebSocketServlet的
	var url = getWsUrl() + "/websocket/anything?userId=" + userId;
	console.log(url);

	// 创建WebSocket实例，下面那个MozWebSocket是Firefox的实现,EsWebSocket为宜搜webview中的实现
	if ('WebSocketFactory' in window) {
		ws = new EsWebSocket(url);
	} else {
		if ('WebSocket' in window) {
			ws = new WebSocket(url);
		} else if ('MozWebSocket' in window) {
			ws = new MozWebSocket(url);
		} else {
			$().alert({
				"content" : "不支持WebSocket,无法开始游戏"
			});
			alert('Unsupported.');
			return;
		}
	}

	ws.onopen = function() {
		console.log("socket连接成功");
	};

	// 收到服务器发送的文本消息, event.data表示文本内容
	ws.onmessage = function(event) {
		queue.push(event);
		queue.notify();
	};
	// 关闭WebSocket的回调
	ws.onclose = function() {
		dataStorage.set(OtherThing.isGameOnGoing, "false");// 标记游戏非进行中
		console.log("socket断开：" + event);
		if (!reconnectCountUpToMax()) {
			setTimeout(connectToServer, 2000);
			// 增加断线重连记数器
			addReconnectCount();
		}else{
			$().alert({
				"content" : "网络异常，无法连接到服务器"
			});
			console.log("网络异常，无法连接到服务器 -> socket连接重试超过最大次数，不再测试重连");
			window.location.href = getServiceURL() + "/index.jsp?"+(new Date()).getTime();
		}		

		if (dataStorage.get(OtherThing.isOnChangingDesk) == "true") { // 换桌如果出现异常则回到大厅
			console.log("换桌出现问题，直接回到大厅！");
			/*
			 * $(".room").show(); $("#playBox").hide();
			 */
			room.switchToRoom();
			dataStorage.remove(OtherThing.isOnChangingDesk);
		}
	};

	ws.onerror = function(event) {
		$().alert({
			"content" : "socket建立失败，无法开始游戏！"
		});
		console.log("socket建立失败：" + event);
	};
}
// 发送消息给服务器
function sendMessage(dtoObj) {
	try {
		if (ws != null) {
			console.log("send -> " + JSON.stringify(dtoObj));
			ws.send(JSON.stringify(dtoObj));
		} else {
			disconnectTip();
		}
	} catch (e) {
		if (dtoObj) {
			$().alert(
					{
						"content" : "网络连接异常!"
					});
		} else {
			$().alert({
				"content" : "网络连接异常!"
			});
		}
		setTimeout(function(){
			location.reload();
		},3000);
		console.log("异常:" + e.message);
	}

}